package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.ElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    //操作ElasticSearch
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //在Kibana中建立好该索引,执行命令在product-mapping.txt文件中

        //给ES中保存数据
        BulkRequest bulkRequest = new BulkRequest();
        skuEsModels.forEach(e -> {
            //构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(e.getSkuId().toString());
            String s = JSONObject.toJSONString(e);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        //保存数据
        BulkResponse bulk = this.restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
         //处理统计结果
        boolean result = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> item.getId()).collect(Collectors.toList());
        log.info("商品上架完成: {},返回数据： {}",collect, bulk.toString());

        return result;
    }

}
